import subprocess
from PySide6.QtCore import QThread, Signal

class ProcessWorker(QThread):
    output_signal = Signal(str)
    finished_signal = Signal(int)

    def __init__(self, cmd, cwd=None):
        super().__init__()
        self.cmd = cmd
        self.cwd = cwd

    def run(self):
        try:
            proc = subprocess.Popen(
                self.cmd,
                cwd=self.cwd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1
            )
            for line in proc.stdout:
                self.output_signal.emit(line.rstrip())
            proc.stdout.close()
            proc.wait()
            self.finished_signal.emit(proc.returncode)
        except Exception as e:
            self.output_signal.emit(f'运行出错: {e}')
            self.finished_signal.emit(-1) 